<?php
namespace app\shop\controller\goods\ozon;

use app\common\model\shop\AccountModel;
use app\common\model\shop\CategoryModel;
use app\common\model\shop\ozon\OzonGoodsCategoryModel;
use app\common\model\shop\ozon\OzonGoodsFeatureModel;
use app\common\model\shop\ozon\OzonGoodsFeatureValueModel;
use app\common\model\shop\ozon\OzonGoodsModel;
use think\admin\Controller;
use think\admin\helper\QueryHelper;
use think\facade\Db;

/**
 * ozon分类管理
 * @package app\shop\controller\goods\ozon
 * @author xuli
 * @DateTime 2024-10-25 09:50
 */
class Category extends Controller
{
    /**
     * 分类列表
     * @auth true
     * @menu true
     * @author xuli
     * @DateTime 2024-10-25 09:50
     * @return void
     */
    public function index()
    {
        OzonGoodsCategoryModel::mQuery()->layTable(function () {
            $this->title = lang('分类管理');

        }, function (QueryHelper $query) {
            $this->check_account = false;
            $this->check_user = false;
            $pid = $this->request->param('pid', 0);
            $query->where(['pid' => $pid]);
            // 数据列表搜索过滤
            $query->like('name')->equal('pid')->dateBetween('create_at');
        });
    }

    protected function _index_page_filter(&$data)
    {

    }

    /**
     * 同步ozon分类
     * @return void
     */
    public function sync()
    {
        // 获取平台分类
        $ozon_goods_model = new OzonGoodsModel();
        $list = $ozon_goods_model->getCategoryList(2);
        if(!empty($list)) {
            $add_data = [];
            foreach ($list as $k => $v) {
                $add_data[] = [
                    'pid' => $v['description_category_id'],
                    'type_id' => $v['id'],
                    'name' => $v['title'],
                    'status' => $v['disabled'] === false ? 0 : 1,
                    'level' => 1,
                    'path' => '0',
                ];
                foreach ($v['children'] as $kk => $vv) {
                    $add_data[] = [
                        'pid' => $vv['description_category_id'],
                        'type_id' => $vv['id'],
                        'name' => $vv['title'],
                        'status' => $vv['disabled'] === false ? 0 : 1,
                        'level' => 2,
                        'path' => '0/' . $vv['description_category_id'],
                    ];
                    foreach ($vv['children'] as $kkk => $vvv) {
                        $add_data[] = [
                            'pid' => $vvv['description_category_id'],
                            'type_id' => $vvv['id'],
                            'name' => $vvv['title'],
                            'status' => $vvv['disabled'] === false ? 0 : 1,
                            'level' => 3,
                            'path' => '0/' . $vv['description_category_id'] . '/' . $vvv['description_category_id'],
                        ];
                    }
                }
            }
            Db::startTrans();
            try {
                OzonGoodsCategoryModel::mq()->whereIn('status', [0, 1])->delete();
                OzonGoodsCategoryModel::mq()->insertAll($add_data);
                Db::commit();
            } catch (\Exception $th) {
                Db::rollback();
                $this->error(lang('同步失败') . '：' . $th->getMessage());
            }
            $this->success(lang('同步成功'));
        }
    }

    /**
     * 获取分类树
     * @return void
     */
    public function getCategoryTreeV1()
    {
        $search_key = $this->request->param('search_key', '');
        $where = [];
        if(!empty($search_key)) {
            $where[] = ['name', 'like', '%'.$search_key.'%'];
        } else {
            $list = OzonGoodsCategoryModel::getCategoryTree();
            if(!empty($list)) {
                $this->success('分类树列表', ['list' => $list]);
            }
        }
        $list = OzonGoodsCategoryModel::mk()->where($where)->order('id asc')->field('name title,id,pid,path,type_id')->select()->toArray();
        $ids = [];
        foreach ($list as $k => $v) {
            $ids[] = $v['pid'];
        }
        $is_expand = 0;
        $whereOr = [
            ['id', 'in', $ids],
            ['name', 'like', '%'.$search_key.'%'],
        ];
        if(!empty($search_key)) {
            $list = OzonGoodsCategoryModel::mk()->field('name title,id,pid,path,type_id')->where(function($query) use ($whereOr) {
                $query->whereOr($whereOr);
            })->order('id asc')->select()->toArray();
            $is_expand = 1;
        }
        $list = OzonGoodsCategoryModel::categoryTree($list, $is_expand);
        // 处理分类树
        $this->success('分类树列表', ['list' => $list]);
    }

    public function syncAttr()
    {
        $description_category_id = $this->request->param('pid', 0); // 分类父级ID
        $category_id = $this->request->param('type_id', 0); // 分类ID
        $shop_id = 2;

        $attr_list = OzonGoodsFeatureModel::mq()->limit(55, 5)->select()->toArray();

        $ozon_goods_model = new OzonGoodsModel();
        $value_data = $update_feature_data = [];
        foreach ($attr_list as $v) {
            $data = $ozon_goods_model->getAttrValue($shop_id, $v['feature_id'], $description_category_id, $category_id);
            if(!empty($data['data'])) {
                $feature_list = $data['data'];
                unset($data);
                foreach ($feature_list as $vv) {
                    $value_data[] = [
                        'description_category_id' => $description_category_id,
                        'category_id' => $category_id,
                        'feature_id' => $v['feature_id'],
                        'value_id' => $vv['id'],
                        'value' => $vv['value'],
                        'info' => $vv['info'],
                        'picture' => $vv['picture'],
                    ];
                }
                $update_feature_data = ['input_type' => 1]; // 更新特征表输入框类型
                OzonGoodsFeatureModel::mq()->where(['id' => $v['id']])->update($update_feature_data);
            }
        }
        OzonGoodsFeatureValueModel::mq()->insertAll($value_data);
        halt($value_data);
    }

    /**
     * 异步拉取分类下属性信息
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-11-19 14:21
     * @return void
     */
    public function pullAttr()
    {
        $category_id = (int)$this->request->post('id', 0);
        if(empty($category_id) || ($category_id <= 0)){
            $this->error('分类信息错误');
        }
        $category_info = OzonGoodsCategoryModel::mk()->where(['id' => $category_id])->find();
        if(empty($category_info)){
            $this->error('分类信息不存在');
        }
        $this->_queue('异步拉取分类['.$category_info['name'].']下属性信息', 'ozonAttribute attribute '.$category_info['id']);
    }

    /**
     * 异步拉取分类
     * @auth true
     * @Description
     * @author wangqinghui
     * @date 2024-11-19 16:09
     * @return void
     */
    public function pullCategory()
    {
        $this->_queue('异步拉取分类', 'ozonAttribute category');
    }

    /**
     * 获取ozon分类树
     * @Description
     * @author wangqinghui
     * @date 2024-12-10 16:21
     * @return void
     */
    public function getCategoryTree()
    {
        $list = OzonGoodsCategoryModel::getCategoryTree();
        if(!empty($list)) {
            $this->success('分类树列表', ['list' => $list]);
        }
        $list = OzonGoodsCategoryModel::mk()->field('name title,id,pid,path,type_id')->select()->toArray();
        $list = OzonGoodsCategoryModel::categoryTree($list);
        // 处理分类树
        $this->success('分类树列表', ['list' => $list]);
    }
}